# coding:utf-8

import pandas as pd
from statsmodels.tsa.arima_model import ARIMA
from statsmodels.tsa.stattools import adfuller as ADF
from statsmodels.stats.diagnostic import acorr_ljungbox

# 日期,销量
data_source = pd.read_excel("arima_data.xls")
inputs = pd.Series(data_source["销量"].values, index=data_source["日期"].values)

# 原始序列
# 平稳性检查,单位根检测p值,0.9983759421514264
print("原始序列,平稳性检查,p值=" , ADF(inputs)[1])

# 1阶差分
d_inputs = inputs.diff(1).dropna()
# 0.02267343544004886
print("1阶差分,平稳性检查,p值=" , ADF(d_inputs)[1])
# 0.0007733936608452891
print("1阶差分,白噪声检查,p值=", acorr_ljungbox(d_inputs, lags=1)[1][0])

# 阶数确定为1

# 搜寻最优p值及q值
bic_matrix = []
for p in range(5):
    tmp = []
    for q in range(5):
        try:
            tmp.append(ARIMA(inputs, (p, 1, q)).fit().bic)
        except:
            tmp.append(None)
    bic_matrix.append(tmp)
p, q = pd.DataFrame(bic_matrix).stack().idxmin()
# 0,1
print("p,q值为", p, q)

# order=(p,d,q)
model = ARIMA(inputs, order=(p, 1, q)).fit()

'''
(array([4873.96657031, 4923.92272193, 4973.87887355, 5023.83502517,
       5073.79117679]), array([ 73.08574327, 142.32679131, 187.54280892, 223.80280345,
       254.95702478]), array([[4730.72114572, 5017.21199491],
       [4644.96733694, 5202.87810693],
       [4606.30172251, 5341.45602459],
       [4585.18959077, 5462.48045957],
       [4574.08459061, 5573.49776296]]))
'''
# 预测
print(model.forecast(5))
